package webapi

import (
	"log"
	"math"
	"net/http"
	"server/global"
	"server/internal/middleware"
	"server/internal/model"
	"server/internal/pkg/WxOfficialAccount"
	"server/internal/pkg/response"
	"server/internal/pkg/wxpay"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// UserApi 用户管理
var UserApi = new(userApi)

type userApi struct {
}

// Router 路由
func (a userApi) Router(r *gin.RouterGroup) {
	api := r.Group("/index", middleware.LoginVerification)
	api.GET("/index", a.index)
	api.POST("/lingqu", a.lingqu)
	api.GET("/get_jssdk", a.get_jssdk)

	api2 := r.Group("/index")
	api2.POST("/notice", a.notice)
}

// index 查询红包
func (userApi) index(c *gin.Context) {
	Db := global.GL_DB //初始化Db

	userInfo := c.MustGet("userInfo").(model.User)
	now := time.Now() // 获取当前时间
	// 计算前一天的时间（减去24小时）
	oneDayAgo := now.Add(-24 * time.Hour).Format("2006-01-02")

	var userBill []model.UserBill
	Db.Model(&userBill).Where("openid = ? and date = ?", userInfo.Openid, oneDayAgo).Find(&userBill)
	response.Success(c, userBill, "")
}

// get_jssdk
func (userApi) get_jssdk(c *gin.Context) {
	url := c.Query("url")
	config, err := WxOfficialAccount.GetJsSdk(url)
	if err != nil {
		response.Error(c, err.Error())
		return
	}

	response.Success(c, config, "")
}

func (userApi) lingqu(c *gin.Context) {
	type Param struct {
		ID int `json:"id"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Error(c, "参数错误", err.Error())
		return
	}
	Db := global.GL_DB
	userBill := model.UserBill{}
	Db.Model(&userBill).Where("id = ?", param.ID).Find(&userBill)
	if userBill.ID == 0 {
		response.Error(c, "记录不存在")
		return
	}

	if userBill.Status == 1 {
		response.Error(c, "无法重复领取")
		return
	}
	if userBill.Status == 0 {
		// 发红包
		transferbatch, err := wxpay.Transfer(int64(math.Floor((userBill.Amount)*100.00)), userBill.Openid, userBill.OrderNo)
		if err != nil {
			response.Error(c, err.Error())
			return
		} else {
			response.Success(c, transferbatch, "")
			return
		}
	}
	response.Error(c, "错误")
}

// notice 支付回调
func (userApi) notice(c *gin.Context) {

	p, err := wxpay.Notice(c)
	if err != nil {
		log.Println("微信支付回调:", err)
		return
	}
	if p.State == "SUCCESS" {
		order_no := p.OutBillNo

		orderNoArr := strings.Split(order_no, "-")
		Db := global.GL_DB
		userBill := model.UserBill{}
		Db.Model(&userBill).Where("order_no = ?", orderNoArr[0]).Find(&userBill)
		if userBill.ID == 0 {
			log.Println("转账回调：", order_no, "，订单号不存在")
			return
		}
		if userBill.Status == 1 {
			c.JSON(200, gin.H{"code": "SUCCESS", "message": "成功"})
			return
		}

		err = Db.Transaction(func(tx *gorm.DB) error {
			//修改状态
			if err = tx.Model(&userBill).Updates(map[string]any{
				"status": 1,
			}).Error; err != nil {
				return err
			}

			// 返回 nil 提交事务
			return nil
		})

		if err != nil {
			log.Println("转账回调：", err)
		}
		c.Status(http.StatusOK)
	} else {
		log.Println("转账回调：", p)
	}

}
